package com.ms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ms.constant.MessageTypeConstant;
import com.ms.constant.MusicStatusConstant;
import com.ms.domain.dto.ReviewDTO;
import com.ms.domain.entity.Music;
import com.ms.exception.BusinessException;
import com.ms.exception.ResourceNotFoundException;
import com.ms.mapper.MusicMapper;
import com.ms.service.AuditService;
import com.ms.service.MessageService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Slf4j
@RequiredArgsConstructor
public class AuditServiceImpl implements AuditService {

    private final MusicMapper musicMapper;
    private final MessageService messageService;

    /**
     * 获取待审核的音乐
     *
     * @param page 页码
     * @param size 每页大小
     * @return 待审核的音乐分页
     */
    @Override
    @Cacheable(value = "audit", key = "#page + '-' + #size",
            unless = "#result == null || #result.isEmpty()")
    public Page<Music> getPendingMusic(Integer page, Integer size) {
        Page<Music> pageInfo = new Page<>(page, size);
        QueryWrapper<Music> query = new QueryWrapper<>();
        query.eq("status", MusicStatusConstant.PENDING)
                .orderByAsc("create_time");

        musicMapper.selectPage(pageInfo, query);
        return pageInfo;
    }

    /**
     * 审核音乐
     *
     * @param dto 审核信息
     */
    @Override
    @Transactional
    public void reviewMusic(ReviewDTO dto) {
        Music music = musicMapper.selectById(dto.getMusicId());
        if (music == null) {
            throw new ResourceNotFoundException("音乐不存在");
        }

        if (!MusicStatusConstant.PENDING.equals(music.getStatus())) {
            throw new BusinessException("音乐状态不可审核");
        }

        // 更新状态
        Music updateEntity = new Music();
        updateEntity.setId(dto.getMusicId());
        updateEntity.setStatus(dto.getStatus());
        musicMapper.updateById(updateEntity);

        // 发送通知
        String message = "您的音乐《" + music.getTitle() + "》";
        if (MusicStatusConstant.APPROVED.equals(dto.getStatus())) {
            message += "已通过审核";
        } else {
            message += "未通过审核。\n原因：" + dto.getFeedback();
        }

        String[] creatorIds = music.getCreatorIds().split("-");
        for (String creatorId : creatorIds) {
            messageService.sendMessage(Integer.valueOf(creatorId), "审核通知", MessageTypeConstant.AUDIT, message, dto.getMusicId());
        }
    }
}
